package com.peas.platform.framework.mybatisplus.config;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.peas.platform.common.core.configuration.RequestContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;
import java.util.function.Supplier;

@Component
@Slf4j
public class CustomAutoFill implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        String userId = RequestContextUtil.getCurrentUserId();
        if (userId != null) {
            this.strictInsertFill(metaObject, "createBy", Long.class, Long.parseLong(userId));
            this.strictInsertFill(metaObject, "updateBy", Long.class, Long.parseLong(userId));
        }
        this.strictInsertFill(metaObject, "createTime", Date.class, DateUtil.date());
        this.strictInsertFill(metaObject, "updateTime", Date.class, DateUtil.date());
        this.strictInsertFill(metaObject, "deleted", Integer.class, 0);
        this.strictInsertFill(metaObject, "version", Integer.class, 1);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String userId = RequestContextUtil.getCurrentUserId();
        if (userId != null) {
            this.strictInsertFill(metaObject, "updateBy", Long.class, Long.parseLong(userId));
        }
        this.strictInsertFill(metaObject, "updateTime", Date.class, DateUtil.date());
    }

    @Override
    public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) {
        // 原方法，当填充字段不是null时，不会进行填充。即前端更新时携带了旧的update信息，就不会填充update
        Object obj = fieldVal.get();
        if (Objects.nonNull(obj)) {
            metaObject.setValue(fieldName, obj);
        }
        return this;
    }

}
